# pylint: disable=unused-import

from pprint import pprint

import Talker
from nmea import NMEASentence, TalkerSentence, ChecksumError


class InputParser:

    @staticmethod
    def RudderControl(RudderAnglePS: float, RudderAngleSB: float,
                      talkID='XX', sentenceType='ROA', checkSum=False,
                      newLine=False, returnAsByte=False):
        """舵令
            Format:
            ----------
                $XXROA
                [$XXROA]
                Format=$XXROA,%f,%f
                1=RudderAnglePS
                2=RudderAngleSB
        """
        RudderAnglePS = str(RudderAnglePS)
        RudderAngleSB = str(RudderAngleSB)
        ans = TalkerSentence(
            talkID, sentenceType, (RudderAnglePS, RudderAngleSB)
        )
        ansStr = ans.render(checksum=checkSum, newline=newLine)
        if returnAsByte:
            return bytes(ansStr, 'ascii')
        else:
            return ansStr

    @staticmethod
    def TelegraphControl(TelegraphPSIn: int, TelegraphSBIn: int,
                         talkID='HW', sentenceType='TEL', checkSum=False,
                         newLine=False, returnAsByte=False):
        """车钟档位
            Format:
            ----------
                $HWTEL
                [$HWTEL]
                Format=$HWTEL,%d,%d
                1=TelegraphPSIn
                2=TelegraphSBIn
        """
        TelegraphPSIn = str(TelegraphPSIn)
        TelegraphSBIn = str(TelegraphSBIn)
        ans = TalkerSentence(
            talkID, sentenceType, (TelegraphPSIn, TelegraphSBIn)
        )
        ansStr = ans.render(checksum=checkSum, newline=newLine)
        if returnAsByte:
            return bytes(ansStr, 'ascii')
        else:
            return ansStr


class OutputParser:

    latestParseResult = None

    @staticmethod
    def parse(line: str, check=False):
        line = line.replace(' ', '')
        try:
            talkerSentence = NMEASentence.parse(line, check)
            OutputParser.latestParseResult = talkerSentence.extract()
        except Exception as err:
            raise err
        # print(repr(talkerSentence))
        # return talkerSentence.extract()


def test():
    # 解析一个 NMEA 报文数据
    with open(r'./TestData.txt') as f:
        lines = f.readlines()
    for line in lines:
        try:
            print('原始串:', line)
            OutputParser.parse(line, check=False)
            print('解析结果:')
            pprint(OutputParser.latestParseResult)
        except ChecksumError as err:
            print('错误:', err)
    # 发送一个 NMEA 报文数据
    ans = InputParser.TelegraphControl(10, 21, checkSum=True)
    print('\n待发送的报文串:')
    pprint(ans)


if __name__ == "__main__":
    test()
